import axios, { AxiosInstance, AxiosResponse } from "axios";
import type { KiRequestInterceptors, KiRequestConfig } from './type'
import { ElLoading } from 'element-plus'
import 'element-plus/theme-chalk/el-loading.css'
const DEFAULT_SHOW = true
class KiRequest {
  instance: AxiosInstance
  interceptors?: KiRequestInterceptors
  isShowLoading: Boolean
  loading?:any
  constructor(config: KiRequestConfig) {

    this.instance = axios.create(config)
    this.interceptors = config.interceptors
    this.isShowLoading = config.isShowLoading || DEFAULT_SHOW
    //创建出的实例特有的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestErrorInterceptor
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseErrorInterceptor
    )
    
    //所有实例的拦截器
    this.instance.interceptors.request.use(config => {
      return config
    }, err => {
      return err
    })
    
    this.instance.interceptors.response.use(res => {
      return res.data
    }, err => {
      return err
    })

    this.instance.interceptors.request.use(
      (config) => {
        if (this.isShowLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在请求数据....',
            background: 'rgba(0, 0, 0, 0.5)'
          })
        }
        return config
      },
      (err) => {
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res) => {
        // 将loading移除
        this.loading?.close()

        if (res.data.returnCode === '-1001') {
          console.log('请求失败~, 错误信息')
        } else {
          return res
        }
      },
      (err) => {
        // 将loading移除
        this.loading?.close()

        // 例子: 判断不同的HttpErrorCode显示不同的错误信息
        if (err.response.status === 404) {
          console.log('404的错误~')
        }
        return err
      }
    )
  }
  request(config:KiRequestConfig):Promise<AxiosResponse> {
    return new Promise((resolve, reject) => {
      if (this.interceptors?.requestInterceptor) {
        config = this.interceptors.requestInterceptor(config)
      }
      this.instance.request(config).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err)
        return err
      })
    })
  }
  get(config: KiRequestConfig) {
    return this.request({
      ...config,
      method:"GET"
    })
  }
  post(config: KiRequestConfig) {
    return this.request({
      ...config,
      method:"POST"
    })
  }
  delete(config: KiRequestConfig) {
    return this.request({
      ...config,
      method:"DELETE"
    })
  }
  patch(config: KiRequestConfig) {
    return this.request({
      ...config,
      method:'PATCH'
    })
  }
}

export default KiRequest